<?php

App::uses('AppController', 'Controller');
App::import('Sanitize');
App::import('Lib', 'ImageUploader');
App::import('Model', 'OnepieceRawModel');
App::import('Model', 'OnepieceQuizModel');
App::import('Vendor', 'simple_html_dom');
App::uses('File', 'Utility');

class AdminonepiecequizController extends AppController {

    public $name = 'Adminonepiecequiz';
    //public $uses = array('OnepieceQuiz');
    public $uses = array('OnepieceRaw');
    /*
      protected $img_resolution_pc=array('size' => '500x500', 'ext' => 'jpg');
      protected $img_resolution_sp=array('size' => '300x300', 'ext' => 'jpg');
     */
    protected $img_check_pattern = array('ext' => 'jpg', 'size' => '500x500');

    function beforeFilter() {
        if (DEBUG_MODE) {
            error_log(__FILE__ . " " . __LINE__);
        }
        $this->layout = 'admin';
        $session_user = $this->Session->read(SESSION_USER);
        if (empty($session_user) && $this->action != 'login') {
		  
            $this->redirect(ADMIN_HOME_URL . 'login?returnurl=' . urlencode(RETURN_URL));
			  
        }

        $this->set('img_check_pattern', $this->img_check_pattern);
    }

    public function index() {
		$this->viewVars['title_for_layout'] = 'クイズ一覧';
        $data = null;
        if ($this->request->is('get')) {
            if (isset($this->params['url']['quizgen'])) {
                $this->genQuizsFromCrawlData($this->params['url']['quizgen']);
            }
            $tmpQuiz = new OnepieceQuizModel();
            if (isset($this->params['url']['page']) && (int) $this->params['url']['page']) {
                $page = $this->params['url']['page'];
            } else { //neu chua xac dinh, thi tim so trang
                if (isset($sql_search_condition)) {
                    $tmp = $tmpQuiz->query("SELECT COUNT(onepiecequiz_id) FROM onepiecequiz $sql_search_condition");
                } else if (isset($searchstatus)) {
                    $tmp = $tmpQuiz->query("SELECT * FROM onepiecequiz");
                } else {
                    $tmp = $tmpQuiz->query("SELECT COUNT(onepiecequiz_id) FROM onepiecequiz");
                }
                $record = $tmp['0']['0']['COUNT(onepiecequiz_id)'];
                if ($record > ROW_PER_PAGE) {
                    $page = ceil($record / ROW_PER_PAGE);
                } else {
                    $page = 1;
                }
            }
            $start = (isset($this->params['url']['start']) && (int) $this->params['url']['start'] >= 0) ? $this->params['url']['start'] : 0;
            $ROW_PER_PAGE = ROW_PER_PAGE;
            if (isset($sql_search_condition)) {
                $data = $tmpQuiz->query("SELECT * FROM onepiecequiz $sql_search_condition ORDER BY onepiecequiz_id ASC LIMIT $start, $ROW_PER_PAGE");
            } else {
                $data = $tmpQuiz->query("SELECT * FROM onepiecequiz ORDER BY onepiecequiz_id ASC LIMIT $start, $ROW_PER_PAGE");
            }
            // check show gen quiz button
            $quizNum = $tmpQuiz->find('count');
            $tmpQuiz = new OnepieceRawModel();
            $rawNum = $tmpQuiz->find('count');
     
            $this->set('isShowGenQuiz', ($quizNum < $rawNum));
            $this->set('Quizs', $data);
            $this->set('page', $page);
            $this->set('display', ROW_PER_PAGE);
            $this->set('start', $start);
        }
    }
	
    public function genQuizsFromCrawlData($number = 100) {
        $startQIndex = -1;
        // read file to get current index
        $filename = 'onepiece_crawl_status.txt';
        $file = new File(IMAGE_UPLOAD_PATH_ONEPIECE . $filename, true, 0644);
        $file_content = $file->read();
        if ($file_content != false) {
            $file_content = trim($file_content);
            if (strlen($file_content) > 4) { // start-end-curQ
                $file_content = explode("-", $file_content);
                $startQIndex = $file_content[2];
            }
        }
        $file->close();
        $tmpRaw = new OnepieceRawModel();
        $result = $tmpRaw->find('first', array(
            'order' => array('data_id' => 'ASC')
        ));

        if ($result == FALSE) {
            return;
        } else {
            $tmpResult = $result["OnepieceRawModel"]['data_id'];
            if ($tmpResult > $startQIndex) {
                $startQIndex = $tmpResult;
            }
            $result = $tmpRaw->find('first', array(
                'order' => array('data_id' => 'DESC')
            ));
            $end_index = $result["OnepieceRawModel"]['data_id'];

            if ($startQIndex > $end_index) {
                return;
            }
            // begin gen
            $listQuestions_en = array(
				'Name this character?'
            );
			
			$listQuestions = array(
				'キャラーの名前は?'
			);
            $listQuestionsSize_en = count($listQuestions_en) - 1;
            $listQuestionsSize = count($listQuestions) - 1;			
            
            $index = 0;
            $saveQIndex = $startQIndex;
            while ($index < $number) {
                if ($saveQIndex > $end_index) {
                    break;
                }
                $result = $tmpRaw->find('first', array(
                    'conditions' => array('data_id' => $saveQIndex)
                ));
                $saveQIndex++;
                if ($result == FALSE) {
                    continue;
                } else {
                    // random correct answer
                    $answer = rand(1, 4);
                    $choices_en = array();
                    $choices_en['choice' . $answer] = $result["OnepieceRawModel"]['name_en'];
                    $choices = array();
                    $choices['choice' . $answer] = $result["OnepieceRawModel"]['name'];
					
                    // random choices
                    $ranChoice = $tmpRaw->find('all', array(
						'fields' => array('name','name_en'),
                        'conditions' => array('data_id !=' => ($saveQIndex - 1)),
                        'order' => 'rand()',
                        'group' => 'data_id',
                        'limit' => 3
                    ));
                    for ($i = 1; $i < 5; $i++) {
                        if ($i != $answer) {
                            while (TRUE) {
                                $cur = rand(0, 2);
                                if ($ranChoice[$cur] != '') {
                                    $choices_en['choice' . $i] = $ranChoice[$cur]["OnepieceRawModel"]['name_en'];
									$choices['choice' . $i] = $ranChoice[$cur]["OnepieceRawModel"]['name'];
                                    $ranChoice[$cur] = '';
                                    break;
                                }
                            }
                        }
                    }
                    $question_en = $listQuestions_en[rand(0, $listQuestionsSize_en)];
					$question = $listQuestions[rand(0, $listQuestionsSize)];
                    $tmpQuiz = new OnepieceQuizModel();
                    $tmpQuiz->set(array(
                        'question_en' => $question_en,
						'question' => $question,
						'choice1' => $choices['choice1'],
                        'choice2' => $choices['choice2'],
                        'choice3' => $choices['choice3'],
                        'choice4' => $choices['choice4'],
                        'choice1_en' => $choices_en['choice1'],
                        'choice2_en' => $choices_en['choice2'],
                        'choice3_en' => $choices_en['choice3'],
                        'choice4_en' => $choices_en['choice4'],
                        'answer' => $answer,
                        'status' => 1,
                        'img_name' => $result["OnepieceRawModel"]['img_name'],
                    ));

                    if (($tmpQuiz->save()) != FALSE) {
                        $index++;
                    }
                }
            }
            // write to file
            if ($saveQIndex > $startQIndex) {
                $file = new File(IMAGE_UPLOAD_PATH_ONEPIECE . $filename, true, 0644);
                $file_content = $file->read();
                if ($file_content != false) {
                    $file_content = trim($file_content);
                    $lastpos = strrpos($file_content, '-');
                    if ($lastpos !== false && $lastpos > 2) {
                        $file_content = substr($file_content, 0, $lastpos);
                    }
                    $file_content = $file_content . '-' . $saveQIndex;
                    $file->write($file_content);
                }
                $file->close();
            }
        }
    }

    public function add() {
        $this->viewVars['title_for_layout'] = '新規登録';
        $this->set('quiz_statuses', GlobalVar::get_quiz_statuses());
        $this->set('quiz_answers', GlobalVar::get_quiz_answers());
        // submit button pressed
        if ($this->request->isPost()) {
            // cancel button pressed
            if (isset($this->data['cancel'])) {
                $this->redirect(ADMIN_ROOT_URL . 'adminonepiecequiz/index');
                return;
            }

            $question_en = $this->request->data('question_en');
            $choice1_en = $this->request->data('choice1_en');
            $choice2_en = $this->request->data('choice2_en');
            $choice3_en = $this->request->data('choice3_en');
            $choice4_en = $this->request->data('choice4_en');
			
			$question = $this->request->data('question');
            $choice1 = $this->request->data('choice1');
            $choice2 = $this->request->data('choice2');
            $choice3 = $this->request->data('choice3');
            $choice4 = $this->request->data('choice4');
			
            $answer = $this->request->data('answer');
            $level = $this->request->data('level');
            $status = $this->request->data('status');
            $image = $this->request->data('image');

            $extra_info = $this->request->data('extra_info');
            $tmpQuiz = new OnepieceQuizModel();

            // upload image
            if (isset($this->data['save'])) {
                $msg = '';
                $upload_image_err = '';


                if (!isset($error)) {
                    $saved_quiz = $tmpQuiz->save($this->request->data);
                }

                if (isset($saved_quiz)) {
                    $msg .= "クイズが登録できました。";
                    $saved_quiz = $saved_quiz['OnepieceQuiz'];
                    if (isset($this->params['form']['image']['name']) && !empty($this->params['form']['image']['name'])) {
                        $uploader = new ImageUploader(IMAGE_UPLOAD_PATH_ONEPIECE, $this->params['form']['image'], 'onepiecequiz_' . $saved_quiz['onepiecequiz_id'], $this->img_check_pattern);
                    	$upload_result = $uploader->upload();
                        if (!$upload_result) {
                            $upload_image_err = $uploader->get_error_message();
                            $msg.= "画像をアップロードできません。";
                            //                        $error = true;					
                        } else {
                            $_img_timestamp = time();
                            $result_query = $tmpQuiz->query("UPDATE onepiecequiz SET img_timestamp=$_img_timestamp, img_name='onepiecequiz_" . $saved_quiz['onepiecequiz_id'] . "." . $this->img_check_pattern["ext"] . "' WHERE onepiecequiz_id = " . $saved_quiz['onepiecequiz_id'] . " LIMIT 1");
                            if (DEBUG_MODE) {
                                GamifyLogger::getLogger()->info($this->params['controller'] . '->' . __FUNCTION__ . ": update query result=" . var_export($result_query, true));
                            }
                        }
                    }


                    $this->Session->setFlash(GlobalVar::get_html_success($msg));
                    $this->set('save_success', true);

                    $this->set('onepiecequiz_id', $saved_quiz['onepiecequiz_id']);
                    $this->set('question', $saved_quiz['question']);
                    $this->set('choice1', $saved_quiz['choice1']);
                    $this->set('choice2', $saved_quiz['choice2']);
                    $this->set('choice3', $saved_quiz['choice3']);
                    $this->set('choice4', $saved_quiz['choice4']);
                    $this->set('question_en', $saved_quiz['question_en']);
                    $this->set('choice1_en', $saved_quiz['choice1_en']);
                    $this->set('choice2_en', $saved_quiz['choice2_en']);
                    $this->set('choice3_en', $saved_quiz['choice3_en']);
                    $this->set('choice4_en', $saved_quiz['choice4_en']);
                    $this->set('answer_selected', $saved_quiz['answer']);
                    $this->set('level_selected', $saved_quiz['level']);
                    $this->set('status_selected', $saved_quiz['status']);
                    $this->set('extra_info', $saved_quiz['extra_info']);
                } else {
                    $error = true;
                }

                if (isset($error) && $error) {
                    // Lưu lại các thông số người dùng nhập
                    $this->set('question', $question);
                    $this->set('choice1', $choice1);
                    $this->set('choice2', $choice2);
                    $this->set('choice3', $choice3);
                    $this->set('choice4', $choice4);
                    $this->set('question_en', $question_en);
                    $this->set('choice1_en', $choice1_en);
                    $this->set('choice2_en', $choice2_en);
                    $this->set('choice3_en', $choice3_en);
                    $this->set('choice4_en', $choice4_en);
                    $this->set('answer_selected', $saved_quiz['answer']);
		    $this->set('level_selected', $saved_quiz['level']);
                    $this->set('status_selected', $saved_quiz['status']);
                    $this->set('extra_info', $extra_info);
                    $this->set('errors_image', $upload_image_err);
                    $this->set('save_success', false);
                    $this->Session->setFlash(GlobalVar::get_html_error("登録ができません。もう一度お願いします。"));
                    $errors = $tmpQuiz->validationErrors;
                    foreach ($errors as $key => $err) {
                        if (!empty($errors[$key]))
                            $this->set('errors_' . $key, $err[0]);
                    }
                }
            }
        }
    }

    public function edit($id = null) {
        $this->set('quiz_statuses', GlobalVar::get_quiz_statuses());
        $this->set('quiz_answers', GlobalVar::get_quiz_answers());

        $quiz_id = $this->request->data('onepiecequiz_id');

		$question = $this->request->data('question');
        $choice1 = $this->request->data('choice1');
        $choice2 = $this->request->data('choice2');
        $choice3 = $this->request->data('choice3');
        $choice4 = $this->request->data('choice4');
		
        $question_en = $this->request->data('question_en');
        $choice1_en = $this->request->data('choice1_en');
        $choice2_en = $this->request->data('choice2_en');
        $choice3_en = $this->request->data('choice3_en');
        $choice4_en = $this->request->data('choice4_en');
        $answer = $this->request->data('answer');
        $status = $this->request->data('status');
        $extra_info = $this->request->data('extra_info');
        $tmpQuiz = new OnepieceQuizModel();

        if ($this->request->isPost()) {

            //back to list
            if (isset($this->data['cancel'])) {
                $this->redirect(ADMIN_ROOT_URL . 'adminonepiecequiz/index');
                return;
            }

            if (isset($this->data['update'])) {
                if (!empty($question_en)) {
                    $quiz_id = trim($quiz_id);
                    // create array
                    $quizData = array();
                    $quizData['onepiecequiz_id'] = $quiz_id;
                    
					$quizData['question'] = $question;
                    $quizData['choice1'] = $choice1;
                    $quizData['choice2'] = $choice2;
                    $quizData['choice3'] = $choice3;
                    $quizData['choice4'] = $choice4;
		    		
					$quizData['question_en'] = $question_en;
                    $quizData['choice1_en'] = $choice1_en;
                    $quizData['choice2_en'] = $choice2_en;
                    $quizData['choice3_en'] = $choice3_en;
                    $quizData['choice4_en'] = $choice4_en;
		    		$quizData['level'] = 1;
                    $quizData['extra_info'] = $extra_info;
                    $quizData['answer'] = $answer;
                    $quizData['status'] = $status;

                    $result_query = $this->saveQuiz($quizData);
                    if (DEBUG_MODE) {
                        GamifyLogger::getLogger()->info($this->params['controller'] . '->' . __FUNCTION__ . ": update query result=" . var_export($quizData, true));
                    }
                    $msg = "データが更新しました。";
                } else {
                    $data = array('onepiecequiz_id' => $quiz_id,
                        'question' => $question,
                        'choice1' => $choice1,
                        'choice2' => $choice2,
                        'choice3' => $choice3,
                        'choice4' => $choice4,
                        'question_en' => $question_en,
                        'choice1_en' => $choice1_en,
                        'choice2_en' => $choice2_en,
                        'choice3_en' => $choice3_en,
                        'choice4_en' => $choice4_en,
                        'answer' => $answer,
                        'status' => $status,
                        'extra_info' => $extra_info
                    );
                    $this->Session->setFlash(GlobalVar::get_html_error("登録ができません。もう一度お願いします。"));
                    $this->set('Quiz', $data);

                    foreach ($data as $key => $err) {
                        if (empty($data[$key]))
                            $this->set('errors_' . $key, '空ではありません。');
                    }
                }

                if (isset($this->params['form']['image']['name']) && !empty($this->params['form']['image']['name'])) {
                    $uploader = new ImageUploader(IMAGE_UPLOAD_PATH_ONEPIECE, $this->params['form']['image'], 'onepiecequiz_' . $quiz_id, $this->img_check_pattern);
                    $upload_result = $uploader->upload();
                    if (!$upload_result) {
                        $upload_image_err = $uploader->get_error_message();
                        $msg.= "画像をアップロードできません。";
                        $this->set('errors_image', $upload_image_err);
                    } else {
                        $_img_timestamp = time();
                        $result_query = $tmpQuiz->query("UPDATE onepiecequiz SET img_timestamp=$_img_timestamp, img_name='onepiecequiz_" . $quiz_id . "." . $this->img_check_pattern["ext"] . "' WHERE onepiecequiz_id = " . $quiz_id . " LIMIT 1");
                        if (DEBUG_MODE) {
                            GamifyLogger::getLogger()->info($this->params['controller'] . '->' . __FUNCTION__ . ": update query result=" . var_export($result_query, true));
                        }
                    }
                }



                if (isset($msg)) {
                    $this->Session->setFlash(GlobalVar::get_html_success($msg));
                    //$this->set('Quiz', $quiz_data);
                    $this->redirect(ADMIN_ROOT_URL . 'adminonepiecequiz/edit/' . $quiz_id);
                    return;
                }
            }
        } else {
            $data = $tmpQuiz->findByOnepiecequizId($id);
            if (is_array($data))
                $data = array_shift($data);
            $this->set('Quiz', $data);
        }
    }

    public function doupdate() {
        if ($this->request->isPost()) {
            $data_status = $this->data['datastatus'];
            $statusarr = explode(",", $data_status);

            foreach ($statusarr as $key => $val) {
                $quiz_status_arr = explode("_", $val);
                $tmpModel = new OnepieceQuizModel();
                $data = $tmpModel->find('first', array('conditions' => array('onepiecequiz_id' => $quiz_status_arr[0],)));
                if (!empty($data)) {
                    $tmpModel->set(array(
                        'onepiecequiz_id' => $quiz_status_arr[0],
                        'status' => $quiz_status_arr[1],
                    ));

                    $tmpModel->save();
                }
            }

            echo json_encode(array("ret" => "OK"));
            exit();
        }
        exit();
    }

    public function delete() {
	$id = $this->params['url']['id'];
        $img_name = $this->params['url']['img_name'];
        
	if (isset($id)) {
         $tmpQuiz = new OnepieceQuizModel();
 	 if (isset($img_name)) {
	   if ($img_name == ('onepiecequiz_' . $id . '.' . $this->img_check_pattern["ext"])) {
                $file = new File(IMAGE_UPLOAD_PATH_ONEPIECE . $img_name, false, 0644);
                if ($file->exists()) {
                    $file->delete();
                    $file->close();
                }
            }
          }
          $tmpQuiz->delete($id);
	}
        $this->redirect(ADMIN_ROOT_URL . 'adminonepiecequiz/index');
    }

    
    public function crawl() {
        $this->viewVars['title_for_layout'] = 'Crawl';
        if ($this->request->isPost()) {
            if (DEBUG_MODE) {
                error_log(__FILE__ . " " . __LINE__);
            }
            $start_charter = $this->request->data('start_charter');
            $end_charter = $this->request->data('end_charter');
            $this->set('start_charter', 0);
            $this->set('end_charter', $end_charter);
            $start_charter = intval($start_charter);
            $end_charter = intval($end_charter);

            set_time_limit(30000);

            $A_CHAR = ord('A');
            $Z_CHAR = ord('Z');
            $start_chunk = $Z_CHAR;
            $end_chunk = $A_CHAR;
            if (($start_charter >= $A_CHAR) && ($end_charter <= $Z_CHAR)) {
                $start_chunk = $start_charter;
                $end_chunk = $end_charter;
            }

			$url_cannon = "http://onepiece.wikia.com/wiki/List_of_canon_characters";
			$url_non_cannon = "http://onepiece.wikia.com/wiki/List_of_non_canon_characters";
			
            $this->getlistcharacters($url_cannon, $start_chunk, $end_chunk);
			$this->getlistcharacters($url_non_cannon, $start_chunk, $end_chunk);            

            // save currently crawl status
            $filename = 'onepiece_crawl_status.txt';
            $file = new File(IMAGE_UPLOAD_PATH_ONEPIECE . $filename, true, 0644);
            $file->write('0-' . $end_charter);
            $file->close();
        }
        $this->crawlindex();
    }

//lay danh sach nhan vat
	protected function getlistcharacters($url, $start_chunk, $end_chunk){
		$letter1 = chr($start_chunk);//start index
		
		//neu end_chunk < Z thi ta tang end_chunk 1 don vi
		//de thiet lap khi gap end_chunk thi dung neu end_chunk = Z thi lay tat ca danh sach bat dau tu start
		//gia su khi lay danh sach nhan vat A->C khi do start_chunk = A
		//end_chunk = C sau do ta tang end_chunk len de khi duyet het C tuc la gap D thi dung
		if($end_chunk < ord('Z')){
			$end_chunk = $end_chunk +1;
			$islimit = true;
		}
		$letter2 = chr($end_chunk);//end index
		$tmpModel = new OnepieceRawModel();
		$node = file_get_html($url);
		if(!is_object($node)){
			return;
		}
		
		$node = $node->find('table[class=wikitable]');
		if (count($node) < 1) {
            return;
        }
		$node = $node[0];
		$node = $node->find('tbody tr');
		$isfind = false;
		foreach ($node as $cur_node){
			$cur_node = $cur_node->find('td');
			
			if(count($cur_node) < 2){
				continue;
			}
			$chara = $cur_node[0];
			//lay node chua start_chunk 
			$chara1 = $chara->find('b span[id='.$letter1.']');
			//lay node chua end_chunk
			$chara2 = $chara->find('b span[id='.$letter2.']');
			if(isset($chara1[0])){
				$isfind = true;
			}
			
			//gap end_chunk thi dung khong lay danh sach nhan vat nua
			if(isset($chara2[0]) && isset($islimit) && $islimit){
				break;
			}
			
			if($isfind){
				$year = $cur_node[4]->plaintext;
				$year = intval($year);
				$cur_node = $cur_node[1]->find('a');
				if(count($cur_node) < 1){
					continue;
				}
				$cur_node = $cur_node[0];
				$name_en = $cur_node->title;
				$link = $cur_node->href;
				
				//neu trong db chua ton tai ten thi tiep tuc lay thong tin nhan vat
				if (!$tmpModel->checkExist($name_en)){
					$name_en = htmlspecialchars_decode($name_en);
					$link = "http://onepiece.wikia.com".$link;
					$this->getdetailcharacter($name_en, $link, $year);

				}	
				
			}		
		}
		
	
	}

//lay hinh anh, thong tin nhan vat
	protected function getdetailcharacter($name_en, $url, $year){
		$node = file_get_html($url);
		
		if(!is_object($node)){
			return;
		}
		//lay node chua thong tin
		$node_infor = $node->find('div[id=mw-content-text]');
		if(count($node_infor) < 1){
			return;
		}
		$infor_text = "";
		$infor = $node_infor[0]->first_child ();
		while(is_object($infor) && $infor != null){
			
			if($infor->tag == 'p'){
				$infor_text = $infor->plaintext;
				
				//tim nhung tag <sup> de loai bo
				$sup = $infor->find('sup');
				foreach($sup as $sup_i){
					$sup_text = $sup_i->plaintext;
					$infor_text = str_replace($sup_text, '', $infor_text);
				}
				break;
				
			}
			$infor = $infor->next_sibling();
			
		}

		//lay node chua hinh anh
		$node_img = $node->find('table[class=toccolours]');
		
		if(count($node_img) < 1){
			return;
		}
		$cur_node = $node_img[0];
		$node_name_japan = $cur_node->find('td');
		$name = '';
		foreach($node_name_japan as $name_japan){
			if(isset($isfind) && $isfind){
				$name = $name_japan->plaintext;
				break;
			}
			if(trim($name_japan->plaintext) == "Japanese Name:"){
			$isfind = true;
			}
		}
		
		if(($name == '') || ($name == "N/A")){
			$name = $name_en;
		}
		
		$image_tag = $cur_node->find('a[class=image] img');
		if(count($image_tag) < 1){
			return;
		}
		$image_tag = $image_tag[0];
		$image_url = $image_tag->getAttribute('src');
		$imgW = $image_tag->getAttribute('width');
		$imgH = $image_tag->getAttribute('height');
		$name = htmlspecialchars_decode($name);
		$this->saveIntoDB($name, $name_en, $image_url, $year, $infor_text, $url);
	}
	
	
	//luu du lieu vao db co kiem tra xem hinh anh co ton tai hay khong
	 protected function saveIntoDB($name,$name_en, $imgurl, $year, $infor_text, $url) {
	
		$filename = basename($imgurl);
		$filename = str_replace("%",'',$filename);
        $noimg = '200px-NoPicAvailable.png';
        if ($filename != $noimg) {
            $content = file_get_contents($imgurl);
            $filepath = IMAGE_UPLOAD_PATH_ONEPIECE . $filename;
            file_put_contents($filepath, $content);
			$tmpModel = new OnepieceRawModel();
			$tmpModel->set(array(
				'name_en' => $name_en,
				'name' => $name,
				'link' => $url,
				'year' => $year,
				'img_name' => $filename,
				'info' => $infor_text,
			));
			$tmpModel->save();
		}
		
    }

   

    protected function crawlindex() {
        $tmpModel = new OnepieceRawModel();
        if (isset($this->params['url']['page']) && (int) $this->params['url']['page']) {
            $page = $this->params['url']['page'];
        } else { //neu chua xac dinh, thi tim so trang
            if (isset($sql_search_condition)) {
                $tmp = $tmpModel->query("SELECT COUNT(data_id) FROM onepiece_raw_data $sql_search_condition");
            } else {
                $tmp = $tmpModel->query("SELECT COUNT(data_id) FROM onepiece_raw_data");
            }
            $record = $tmp['0']['0']['COUNT(data_id)'];
            if ($record > ROW_PER_PAGE) {
                $page = ceil($record / ROW_PER_PAGE);
            } else {
                $page = 1;
            }
        }
        $start = (isset($this->params['url']['start']) && (int) $this->params['url']['start'] >= 0) ? $this->params['url']['start'] : 0;

        $ROW_PER_PAGE = ROW_PER_PAGE;
        if (isset($sql_search_condition)) {
            $data = $tmpModel->query("SELECT * FROM onepiece_raw_data $sql_search_condition ORDER BY data_id ASC LIMIT $start, $ROW_PER_PAGE");
        } else {
            $data = $tmpModel->query("SELECT * FROM onepiece_raw_data ORDER BY data_id ASC LIMIT $start, $ROW_PER_PAGE");
        }
        $this->set('onepiece_raw_data', $data);
        $this->set('page', $page);
        $this->set('display', ROW_PER_PAGE);
        $this->set('start', $start);
        if ($this->request->isGet()) {
            // get index
            $filename = 'onepiece_crawl_status.txt';
            $file = new File(IMAGE_UPLOAD_PATH_ONEPIECE . $filename, true, 0644);
            $file_content = $file->read();
            if ($file_content != false) {
                $file_content = trim($file_content);
                if (strlen($file_content) > 2) {
                    $file_content = explode("-", $file_content);
                    $this->set('start_charter', $file_content[0]);
                    $this->set('end_charter', $file_content[1]);
                }
            }
            $file->close();
        }
    }


	
public function crawledit($id = null) {
        $tmpModel = new OnepieceRawModel();
        if ($this->request->isPost()) {
            //back to list
            if (isset($this->data['cancel'])) {
                $this->redirect(ADMIN_ROOT_URL . 'adminonepiecequiz/crawl');
                return;
            }

            if (isset($this->data['update'])) {
                $data_id = $this->request->data('data_id');
                $name = $this->request->data('name');
				$name_en = $this->request->data('name_en');
                $info = $this->request->data('info');
                $year = $this->request->data('year');
                $cur_img_name = $this->request->data('cur_img_name');

                if (!empty($name)) {
                    $data_id = trim($data_id);
                    // create array
                    $tmpData = array();
                    $tmpData['data_id'] = $data_id;
                    $tmpData['name'] = $name;
                    $tmpData['name_en'] = $name_en;					
                    $tmpData['info'] = $info;
                    $tmpData['year'] = $year;

                    $result_query = $this->saveData($tmpData);
                    if (DEBUG_MODE) {
                        GamifyLogger::getLogger()->info($this->params['controller'] . '->' . __FUNCTION__ . ": update query result=" . var_export($tmpData, true));
                    }
                    $msg = "データが更新しました。";
                } else {
                    $data = array('data_id' => $data_id,
                        'name' => $name,
						'name_en' => $name_en,
                        'info' => $info,
                        'year' => $year
                    );
                    $this->Session->setFlash(GlobalVar::get_html_error("登録ができません。もう一度お願いします。"));
                    $this->set('data', $data);

                    foreach ($data as $key => $err) {
                        if (empty($data[$key]))
                            $this->set('errors_' . $key, '空ではありません。');
                    }
                }

                if (isset($this->params['form']['image']['name']) && !empty($this->params['form']['image']['name'])) {
                    $uploader = new ImageUploader(IMAGE_UPLOAD_PATH_ONEPIECE, $this->params['form']['image'], 'data_' . $data_id, $this->img_check_pattern);
                    $upload_result = $uploader->upload();
                    if (!$upload_result) {
                        $upload_image_err = $uploader->get_error_message();
                        $msg.= "画像をアップロードできません。";
                        $this->set('errors_image', $upload_image_err);
                    } else {
                        $image_name = 'data_' . $data_id . "." . $this->img_check_pattern["ext"];
                        $result_query = $tmpModel->query("UPDATE onepiece_raw_data SET img_name='" . $image_name . "' WHERE data_id = " . $data_id . " LIMIT 1");
                        if (isset($cur_img_name) && ($cur_img_name != $image_name)) {
                            $cur_img_name = trim($cur_img_name);
                            if (strlen($cur_img_name) > 0) {
                                $file = new File(IMAGE_UPLOAD_PATH_ONEPIECE . $cur_img_name, false, 0644);
                                if ($file->exists()) {
                                    $file->delete();
                                    $file->close();
                                }
                            }
                        }
                        if (DEBUG_MODE) {
                            GamifyLogger::getLogger()->info($this->params['controller'] . '->' . __FUNCTION__ . ": update query result=" . var_export($result_query, true));
                        }
                    }
                }

                if (isset($msg)) {
                    $this->Session->setFlash(GlobalVar::get_html_success($msg));
                    //$this->set('Quiz', $quiz_data);
                    $this->redirect(ADMIN_ROOT_URL . 'adminonepiecequiz/crawledit/' . $data_id);
                    return;
                }
            }
        } else {
            $data = $tmpModel->findByDataId($id);
            if (is_array($data))
                $data = array_shift($data);
            $this->set('data', $data);
        }
    }

    public function crawldelete() {
        $id = $this->params['url']['id'];
        $img_name = $this->params['url']['img_name'];

        if (isset($id)) {
            $tmpModel = new OnepieceRawModel();
            if (isset($img_name)) {
                $file = new File(IMAGE_UPLOAD_PATH_ONEPIECE . $img_name, false, 0644);
                if ($file->exists()) {
                    $file->delete();
                    $file->close();
                }
            }
            $tmpModel->delete($id);
        }
        $this->redirect(ADMIN_ROOT_URL . 'adminonepiecequiz/crawl');
    }
	
	public function saveData($quizData){
    
        $quizModel = new OnepieceRawModel();
    	if(isset($quizData['data_id'])){
    	   $quizModel->data_id = $quizData['data_id'];
           $current = $quizModel->read(null, $quizData['data_id']);
           if (empty($current)){
                return;
           }
           $current = array_shift($current);
            // sets value to fields
            if (isset($quizData['name']) && !empty($quizData['name'])){
	            $save_data['name'] = $quizData['name'];
			}else {
	            if (isset($current['name'])){
	                $save_data['name'] = $current['name'];
	            } 
	        }
			
			if (isset($quizData['name_en']) && !empty($quizData['name_en'])){
	            $save_data['name_en'] = $quizData['name_en'];
			}else {
	            if (isset($current['name_en'])){
	                $save_data['name_en'] = $current['name_en'];
	            } 
	        }

	        if (isset($quizData['image_name']) && !empty($quizData['image_name'])){
	            $save_data['image_name'] = $quizData['image_name'];
			}
			else {
	            if (isset($current['img_name'])){
	                $save_data['img_name'] = $current['img_name'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['info']) && !empty($quizData['info'])){
	            $save_data['info'] = $quizData['info'];
			}else {
	            if (isset($current['info'])){
	                $save_data['info'] = $current['info'];                        
	            }
	        }
			
			if (isset($quizData['year']) && !empty($quizData['year'])){
	            $save_data['year'] = $quizData['year'];
			}else {
	            if (isset($current['year'])){
	                $save_data['year'] = $current['year'];                        
	            }
	        }
  		}
  		//calls save to db
  		$result = $quizModel->save($save_data);
		if ($result){
		    return true; //"successfully.";
		} else {
		    return false;//"not success";
		}
		//end save data
    }
	
	public function saveQuiz($quizData)
    {
    	$quizModel = new OnepieceQuizModel();
    	if(isset($quizData['onepiecequiz_id']))//sua
      	{
			$quizModel->onepiecequiz_id = $quizData['onepiecequiz_id'];
			$current = $quizModel->read(null, $quizData['onepiecequiz_id']);
			if (empty($current)){				
				return;
			}        
			$current = array_shift($current);
			// sets value to fields
			if (isset($quizData['question']) && !empty($quizData['question'])){
	            $save_data['question'] = $quizData['question'];
			}
			else {
	            if (isset($current['question'])){
	                $save_data['question'] = $current['question'];                        
	            } 
	        }
	        if (isset($quizData['question_en']) && !empty($quizData['question_en'])){
	            $save_data['question_en'] = $quizData['question_en'];
			}
			else {
	            if (isset($current['question_en'])){
	                $save_data['question_en'] = $current['question_en'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['choice1']) && !empty($quizData['choice1'])){
	            $save_data['choice1'] = $quizData['choice1'];
			}
			else {
	            if (isset($current['choice1'])){
	                $save_data['choice1'] = $current['choice1'];                        
	            }
	        }
	        // sets value to fields
			if (isset($quizData['choice1_en']) && !empty($quizData['choice1_en'])){
	            $save_data['choice1_en'] = $quizData['choice1_en'];
			}
			else {
	            if (isset($current['choice1_en'])){
	                $save_data['choice1_en'] = $current['choice1_en'];                        
	            }
	        }
	        // sets value to choice2
			if (isset($quizData['choice2'])){
	            $save_data['choice2'] = $quizData['choice2'];
			}
			else {
				if (isset($current['choice2'])){
	                $save_data['choice2'] = $current['choice2'];                        
	            }
	        }
	        // sets value to choice2_en
			if (isset($quizData['choice2_en']) && !empty($quizData['choice2_en'])){
	            $save_data['choice2_en'] = $quizData['choice2_en'];
			}
			else {
                if (isset($current['choice2_en'])){
	                $save_data['choice2_en'] = $current['choice2_en'];                        
	            }
	        }
	        // sets value to field
			if (isset($quizData['choice3']) && !empty($quizData['choice3'])){
	            $save_data['choice3'] = $quizData['choice3'];
			}
			else {
	            if (isset($current['choice3'])){
	                $save_data['choice3'] = $current['choice3'];                        
	            }
	        }
	        // sets value to fields
			if (isset($quizData['choice3_en']) && !empty($quizData['choice3_en'])){
	            $save_data['choice3_en'] = $quizData['choice3_en'];
			}
			else {
	            if (isset($current['choice3_en'])){
	                $save_data['choice3_en'] = $current['choice3_en'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['choice4']) && !empty($quizData['choice4'])){
	            $save_data['choice4'] = $quizData['choice4'];
			}
			else {
	            if (isset($current['choice4'])){
	                $save_data['choice4'] = $current['choice4'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['choice4_en']) && !empty($quizData['choice4_en'])){
	            $save_data['choice4_en'] = $quizData['choice4_en'];
			}
			else {
	            if (isset($current['choice4_en'])){
	                $save_data['choice4_en'] = $current['choice4_en'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['extra_info']) && !empty($quizData['extra_info'])){
	            $save_data['extra_info'] = $quizData['extra_info'];
			}
			else {
	            if (isset($current['extra_info'])){
	                $save_data['extra_info'] = $current['extra_info'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['answer']) && !empty($quizData['answer'])){
	            $save_data['answer'] = $quizData['answer'];
			}
			else {
	            if (isset($current['answer'])){
	                $save_data['answer'] = $current['answer'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['choice1_num']) && !empty($quizData['choice1_num'])){
	            $save_data['choice1_num'] = $quizData['choice1_num'];
			}
			else {
	            if (isset($current['choice1_num'])){
	                $save_data['choice1_num'] = $current['choice1_num'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['choice2_num']) && !empty($quizData['choice2_num'])){
	            $save_data['choice2_num'] = $quizData['choice2_num'];
			}
			else {
	            if (isset($current['choice2_num'])){
	                $save_data['choice2_num'] = $current['choice2_num'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['choice3_num']) && !empty($quizData['choice3_num'])){
	            $save_data['choice3_num'] = $quizData['choice3_num'];
			}
			else {
	            if (isset($current['choice3_num'])){
	                $save_data['choice3_num'] = $current['choice3_num'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['choice4_num']) && !empty($quizData['choice4_num'])){
	            $save_data['choice4_num'] = $quizData['choice4_num'];
			}
			else {
	            if (isset($current['choice4_num'])){
	                $save_data['choice4_num'] = $current['choice4_num'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['status']) && !empty($quizData['status'])){
	            $save_data['status'] = $quizData['status'];
			}
			else {
	            if (isset($current['status'])){
	                $save_data['status'] = $current['status'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['img_timestamp']) && !empty($quizData['img_timestamp'])){
	            $save_data['img_timestamp'] = $quizData['img_timestamp'];
			}
			else {
	            if (isset($current['img_timestamp'])){
	                $save_data['img_timestamp'] = $current['img_timestamp'];                        
	            } 
	        }
	        // sets value to fields
			if (isset($quizData['img_name']) && !empty($quizData['img_name'])){
	            $save_data['img_name'] = $quizData['img_name'];
			}
			else {
	            if (isset($current['img_name'])){
	                $save_data['img_name'] = $current['img_name'];                        
	            } 
	        }
  		}
  		//calls save to db
  		$result = $quizModel->save($save_data);
		if ($result){
		    return true; //"successfully.";
		} else {
		    return false;//"not success";
		}
		//end save data
    }
	
}